#!/usr/bin/env python
# encoding: utf-8
'''
@author: caopeng
@license: (C) Copyright 1999-2017, Fiberhome Telecommunication Technologies Co.,LTD.
@contact: gjzuo@fiberhome.com
@software: garner
@file: search_file.py.py
@time: 2018/2/7 16:54
@desc:
'''

import sys
reload(sys)
sys.setdefaultencoding('utf8')

import os
import json

def create_games_table(game_path, file_suffix):
    if not game_path or not file_suffix:
        print "game path is empty, please input a valid path!"
        return
    try:
        game_files = os.listdir(game_path)
        #games_table_file = open('game.txt', 'rw')  # 以追加方式打开输出文件
        gameTable = []
        games_number = 0
        for files in game_files:  # 遍历当前目录所有问价和目录
            child = os.path.join(game_path, files)  # 加上路径，否则找不到

            if os.path.isdir(child):  # 如果是目录，则继续遍历子目录的文件
                try:
                    child_files = os.listdir(child)
                    for file in child_files:

                        if os.path.isfile(os.path.join(child, file)) == True and os.path.splitext(os.path.join(child, file))[1] == file_suffix:  # 分割文件名和文件扩展名，并且扩展名为'meta'
                            full_file_path = os.path.join(child, file)  # 同样要加上路径
                            games_number += 1
                            game_obj = {}
                            game_obj["name"] = file.decode("ascii").encode('utf-8')
                            game_obj["executable_file"] = full_file_path.decode("ascii").encode('utf-8')
                            gameTable.append(game_obj)
                except Exception:
                    print 'child path not exists!'

            elif os.path.isfile(child):  # 如果是文件，则直接判断扩展名
                if os.path.splitext(child)[1] == file_suffix:
                    games_number += 1
                    game_obj = {}
                    game_obj["name"] = file.lstrip(game_path).decode("ascii").encode('utf-8')
                    game_obj["executable_file"] = file.decode("ascii").encode('utf-8')
                    gameTable.append(game_obj)

        game_info_obj = {}
        game_info_obj["game_number"] = games_number
        game_info_obj["games_info"] = gameTable

        with open("D:\GameForTest\game.txt", "w+") as f:
            f.write(json.dumps(game_info_obj, ensure_ascii=False))

        return game_info_obj

    except Exception:
        print 'path not exists!'


if __name__ == "__main__":
    games_info = create_games_table('D:\GameForTest', ".exe")
    #print("games_info-->", games_info)